package com.tsyz.shared.util;

import lombok.Getter;
import lombok.Setter;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 异步线程池配置类
 * 企业级线程池配置，用于处理CompletableFuture等异步任务
 */
public class AsyncThreadPoolConfig {
    
    /**
     * 线程池配置参数
     */
    @Setter
    @Getter
    public static class ThreadPoolProperties {
        // Getters and Setters
        // 核心线程数
        private int corePoolSize = 10;
        
        // 最大线程数
        private int maximumPoolSize = 10;
        
        // 空闲线程存活时间（秒）
        private long keepAliveTime = 60L;
        
        // 任务队列容量
        private int queueCapacity = 100;
        
        // 线程名称前缀
        private String threadNamePrefix = "async-pool-";
        
        // 拒绝策略
        private String rejectionPolicy = "CallerRunsPolicy";
        
        public ThreadPoolProperties() {}

    }
    
    /**
     * 创建线程池
     * @param properties 线程池配置属性
     * @return ExecutorService 线程池实例
     */
    public static ExecutorService createThreadPool(ThreadPoolProperties properties) {
        // 创建阻塞队列
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(properties.getQueueCapacity());
        
        // 创建线程工厂
        ThreadFactory threadFactory = new ThreadFactory() {
            private final AtomicInteger threadNumber = new AtomicInteger(1);
            private final String namePrefix = properties.getThreadNamePrefix();
            
            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r, namePrefix + threadNumber.getAndIncrement());
                t.setDaemon(false);
                t.setPriority(Thread.NORM_PRIORITY);
                return t;
            }
        };
        
        // 创建拒绝策略
        RejectedExecutionHandler handler = createRejectedExecutionHandler(properties.getRejectionPolicy());
        
        // 创建线程池
        return new ThreadPoolExecutor(
                properties.getCorePoolSize(),
                properties.getMaximumPoolSize(),
                properties.getKeepAliveTime(),
                TimeUnit.SECONDS,
                workQueue,
                threadFactory,
                handler
        );
    }
    
    /**
     * 根据策略名称创建拒绝策略
     * @param policy 策略名称
     * @return RejectedExecutionHandler 拒绝策略实例
     */
    private static RejectedExecutionHandler createRejectedExecutionHandler(String policy) {
        switch (policy) {
            case "CallerRunsPolicy":
                return new ThreadPoolExecutor.CallerRunsPolicy();
            case "AbortPolicy":
                return new ThreadPoolExecutor.AbortPolicy();
            case "DiscardPolicy":
                return new ThreadPoolExecutor.DiscardPolicy();
            case "DiscardOldestPolicy":
                return new ThreadPoolExecutor.DiscardOldestPolicy();
            default:
                return new ThreadPoolExecutor.CallerRunsPolicy();
        }
    }
    
    /**
     * 默认线程池配置
     * @return ExecutorService 默认线程池实例
     */
    public static ExecutorService createDefaultThreadPool() {
        ThreadPoolProperties properties = new ThreadPoolProperties();
        return createThreadPool(properties);
    }
}
